package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取用户信息
//        Employee employee = (Employee)request.getSession().getAttribute(UserContext.USER_IN_SESSION);
        Employee employee = UserContext.getCurrentUser();



        //判断是否超管
        if(employee.isAdmin()){
            return true;//放行
        }
        // handler如果是handlerMethod类型, 代表被拦截的就是处理方法
       if(handler instanceof HandlerMethod){
            //如果是才强转
           HandlerMethod method = (HandlerMethod)handler;
            //从方法上获取权限注解
           RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
            //判断该方法是否有贴权限注解
           if (annotation==null) {
               return true;//放行
           }
           //获取当前登录用户拥有的权限
//           List<String> expressions = (List<String>)request.getSession().getAttribute("EXPRESSION_IN_SESSION");
           List<String> expressions = UserContext.getExpressions();
           //获取权限注解中的表达式
           String expression = annotation.expression();
           if (!expressions.contains(expression)) { //如果不包含,代表没权限
               //跳转到nopermission页面(直接用request或response跳页面是不会经过视图解析器,需要进入处理方法来跳转)
//               request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
               response.sendRedirect("/nopermission");
               return false; //不放行
           }
       }
        return true; //静态资源, 放行
    }
}
